package com.zlcode.gateway;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Service
public class CookFilterGatewayFilterFactory
        extends AbstractGatewayFilterFactory<CookFilterConfig>
        implements Ordered {

    public CookFilterGatewayFilterFactory() {
        super(CookFilterConfig.class);
    }

    @Override
    public GatewayFilter apply(CookFilterConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                log.info("Pre 请求转发之前查看请求查询参数：" + exchange.getRequest().getQueryParams());
                log.info("Pre 请求转发之前查看 yml 传递的 name 参数：" + config.getName());
                return chain.filter(exchange).then(Mono.fromRunnable(new Runnable() {
                    @Override
                    public void run() {
                        log.info("Post 请求转发之后查看响应状态码：" + exchange.getResponse().getStatusCode());
                    }
                }));
            }
        };
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE; // 设置优先级最低
    }
}
